package com.bcbim.smart_water.weather.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcbim.smart_water.weather.mapper.WeatherMapper;
import com.bcbim.smart_water_interface.weather.dao.WeatherDAO;
import com.bcbim.smart_water_interface.weather.service.WeatherService;
import com.bcbim.smart_water_interface.weather.vo.WeatherAnalysisVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * @description: 气象信息 service 实现类
 * @author: zhangfan
 * @time: 2021/1/18
 */
@Service(timeout = 60 * 1000, group = "weather", version = "1.0.0")
public class WeatherServiceImpl implements WeatherService {
    @Autowired
    private WeatherMapper weatherMapper;

//    public static final String APP_ID = "77355834";         // 用户appid
    public static final String APP_ID = "24681191";         // 用户appid
//    public static final String APP_SECRET = "2t7giH75";     // 用户appsecret
    public static final String APP_SECRET = "7qEFbLo9";     // 用户appsecret
    public static final String CITY_ID = "101030100";       // 城市id：天津

    /**
     * @Description: 获取天气信息
     * @Param: version 天气接口类型
     * @Author: zhangfan
     * @date: 2021/1/18
     */
    public JSONObject listWeather(String version){
        JSONObject jsonData = null;
        try {
            URL url = new URL("http://www.yiketianqi.com/api?version=" + version + "&appid=" + APP_ID + "&appsecret=" + APP_SECRET + "&cityid=" + CITY_ID);
            URLConnection connectionData = url.openConnection();
            connectionData.setConnectTimeout(30000);
            connectionData.setReadTimeout(30000);

            BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "GBK"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();

            jsonData = JSON.parseObject(datas);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonData;
    }

    @Override
    public int insert(WeatherDAO record) {
        return weatherMapper.insert(record);
    }

    @Override
    public List<WeatherAnalysisVO> listWeatherAnalysis() {
        return weatherMapper.listWeatherAnalysis();
    }
}
